#version 150 core

uniform sampler2D diffuseTex;
uniform sampler2D blurTex;
uniform sampler2D depthTex;
uniform float zNear;
uniform float zFar;
uniform int underWater;

in Vertex {
	vec2 texCoord;
} IN;

out vec4 gl_FragColor;

void main(void) {
	float z = texture2D(depthTex, IN.texCoord.xy).x;
	float depth = ((2.0 * zNear) / (zFar + zNear - (z * (zFar - zNear))));

	depth-=1;
	depth*=1000;
	
	float focalPosition = 0.65;
	float focalDistance = 0.35;
	float tolerance = 1;	//Rate of blurryness, smaller means blurs quicker
	
	if(depth<focalPosition-focalDistance){
		float temp = clamp((depth)*(1/(focalPosition-focalDistance)), 0.0, tolerance)/tolerance;
		
		vec4 difblend = texture2D(diffuseTex, IN.texCoord.xy);
		vec4 blurblend = texture2D(blurTex, IN.texCoord.xy);
		gl_FragColor = mix(blurblend, difblend, sin(temp));
	}else if(depth>focalPosition+focalDistance){
		float distanceToStartOfBlur = (depth-(focalPosition+focalDistance));
		float temp = clamp(distanceToStartOfBlur/tolerance, 0.0, 1.0);
		
		vec4 difblend = texture2D(diffuseTex, IN.texCoord.xy);
		vec4 blurblend = texture2D(blurTex, IN.texCoord.xy);
		gl_FragColor = mix(blurblend, difblend, sin(temp));
	}else{
		gl_FragColor = texture2D(diffuseTex , IN.texCoord.xy);
	}
	
	if(underWater == 1){
		gl_FragColor.r-=0.1;
	}
	
}